<template>
 
      <a-spin :spinning="confirmLoading" >
        <a-form-model ref="form" :model="model" :rules="validatorRules">
          <div id="view" style="display:flex"    >
            <div>
              <img id="view1" :style="{height:viewheight+'px',width:viewwidth+'px'}"  src="http://127.0.0.1:38088/video=stream&camidx=0" alt="主摄像头">
              <!-- <div  class="table-operator"> 
                <a-button @click="OpenDeskew()" type="primary" icon="redo">纠偏裁边</a-button>
                <a-button @click="rotate(90)" type="primary" icon="redo">左转</a-button>
                <a-button @click="rotate(270)" type="primary" icon="undo">右转</a-button>  
                <a-button @click="GrabImage()"  :loading="GrabLoading" type="primary" icon="picture"  :disabled="hubmit">拍照</a-button>  
              </div> -->
            </div>
            <div id="container" class="down-tree" :style="{height:viewheight +'px'}" style="overflow-y:auto; width:100%;    display: flex; flex-wrap: wrap;"  > 
              <div :class="'hopic'+index" v-for="(item,index) in imglist" :key="index"   style="margin:5px"  v-viewer="{movable: false}" > 
                <img :id="'img'+index" class='pic' style="width:100px"  :src="'data:image/jpg;base64,' + item " @contextmenu.prevent="onContextmenu"    />  
              </div> 
            </div> 
            <!-- <div>
              <a-col :span="24">
                <a-form-model-item label="纠偏裁边" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="wjmc">
                  <a-switch v-model="rectifying" size="small" default-checked @change="OpenDeskew"/>
                </a-form-model-item>
              </a-col>  
              <a-col :span="24">
                <a-form-model-item label="色彩模式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sx">
                  <a-select v-model="ColorMode" placeholder='色彩模式' style='width: 100px' >
                    <a-select-option :value='item.id' v-for="(item,index) in ColorModeList"  :key='index'>
                                  {{item.name}}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="清晰度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sx">
                  <a-select v-model="quality" placeholder='清晰度' style='width: 100px'  >
                    <a-select-option :value='item.id' v-for="(item,index) in qualitylist"  :key='index'>
                                  {{item.name}}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </div> -->
          </div>
          <!-- 缩略图 https://gyss.going.pub:444/gimg/tx.png-->
          
          <!-- 功能按钮 -->
          <div class="table-operator"> 
            <a-checkbox v-model:checked="rectifying" @change="OpenDeskew">纠偏裁边</a-checkbox><br/><br/>
            <a-button @click="OpenCamera()" :loading="openLoading"  type="primary" icon="file-image">打开高拍仪</a-button>
            <a-button @click="close_view1()" :loading="closeLoading" icon="file-excel">关闭高拍仪</a-button> 
            <a-button @click="rotate(90)" type="primary" icon="redo">左转</a-button>
            <a-button @click="rotate(270)" type="primary" icon="undo">右转</a-button>  
            
            <a-button @click="GrabImage()"  :loading="GrabLoading" type="primary" icon="picture"  :disabled="hubmit">拍照</a-button>  
            <a-button @click="handleOk()" :loading="iconLoading"  type="danger" icon="check-square" >提交</a-button>   
          </div>
          
          <!-- PDF --> 
          <!-- 设备 --> 
          <!-- 操作日志 --> 
        </a-form-model>
      </a-spin>
      
  </template>
  
  <script src="./static/style.js"></script> 
  <script src="./api/serialport.js"></script>
  <script src="./api/pdf.js"></script>
  <script src="./api/person.js"></script>
  <script src="./api/equipment.js"></script>
  <script src="./customized/thumbnail_customized.js"></script>
  
  <script>

    import Vue from 'vue'
    import axios from 'axios' 
    import { validateDuplicateValue } from '@/utils/util'
    import Contextmenu from "vue-contextmenujs" 
    import Viewer from 'v-viewer'
    import 'viewerjs/dist/viewer.css'
    import { mapGetters } from 'vuex' 
    Vue.use(Viewer)
    // 全局配置
    Viewer.setDefaults({
      zIndex: 9999, // 图片查看器的层级
      navbar: false, // 隐藏导航栏
      toolbar: {
        zoomIn: true,
        zoomOut: true,
        oneToOne: true,
        reset: true,
        play: true,
        rotateLeft: true, 
        rotateRight: true,
        flipHorizontal: true,
        flipVertical: true,
      },
    }) 
    Vue.use(Viewer)
    Vue.use(Contextmenu);
    export default {
      name: "WebCamera",
      components: {  
      },
      data () {
        return { 
          iconLoading:false,
          openLoading:false,
          closeLoading:false,
          GrabLoading:false,
          hubmit:false,
          rectifying:false,//摄像头纠偏
          autocamera:false,//自动拍照
          quality:0,//图片质量
          ColorMode:0,//色彩模式
          viewheight:282,
          viewwidth:400,
          disabled:false,
          title:"操作",
          qualitylist:[
            {id:0,name:'默认质量'},
            {id:1,name:'高质量'},
            {id:2,name:'较高质量'},
            {id:3,name:'中等质量'},
            {id:4,name:'较差质量'},
            {id:5,name:'差质量'}, 
          ],
          ColorModeList:[
            {id:0,name:'彩色模式'},
            {id:1,name:'灰色模式'},
            {id:2,name:'黑白模式'},
            {id:3,name:'白纸印章'},
            {id:4,name:'去除背景'}, 
          ],
          width:800,
          rotatv:0,
          modelvisible: false,
          visible: true,
          model:{
           },
          labelCol: {
            xs: { span: 4 },
            sm: { span: 9 },
          },
          wrapperCol: {
            xs: { span: 24 },
            sm: { span: 15 },
          },
          twolabelCol: {
            xs: { span: 4 },
            sm: { span: 5 },
          },
          twowrapperCol: {
            xs: { span: 24 },
            sm: { span: 19 },
          }, 
          confirmLoading: false,
          validatorRules: {
          },
          url: {
            add: "/ml/daMl/add",
            edit: "/ml/daMl/edit",
          },
          expandedRowKeys:[],
          pidField:"pid",
          imglist:[],
          contextMenuData : [
              {
                  label: '运行',
                  icon: 'iconfont icon-zhihang',
                  onClick: () => {
                      this.onRunCode();
                  }
              },
              {
                  label: '运行',
                  icon: 'iconfont icon-sql_exec_new',
                  onClick: () => {
                      this.onRunCodeNewTab();
                  }
              },
          ]
    
        }
      },
      created () {
         //备份model原始值
         this.modelDefault = JSON.parse(JSON.stringify(this.model));
  
      },
      methods: {
        ...mapGetters(["webcamera"]),
        show(){
          console.log("webshow");
          this.iconLoading=false;
          this.openLoading=false;
          this.closeLoading=false;
          this.GrabLoading=false;
          this.hubmit=false;
          this.imglist = [];
          
          setTimeout(() => {         
            this.OpenCamera();  
          }, 2000); 

        },
        // 鼠标右键事件
        onRunCode(){

        },
        onRunCodeNewTab(){
        },
        onContextmenu(event) {
          console.log(event.srcElement.attributes[0].value)
          let id = event.srcElement.attributes[0].value;

          this.$contextmenu({
              items: [
                {
                  label: "预览(B)",
                  onClick: () => { 
                    console.log("返回(B)"); 

                    const viewer = this.$el.querySelector('.hopic'+id.replace("img","")).$viewer
                    viewer.show()
                  }
                },
                { 
                  label: "删除(F)",
                  onClick: () => { 
                    console.log("返回(B)");
                    this.imglist.splice(id.replace("img",""),1);
                  }
                },   
              ],
              event,
              //x: event.clientX,
              //y: event.clientY,
              customClass: "class-a",
              zIndex: 9999,
              minWidth: 230
            });
            return false; 
        },
        deleteimg(index){
          this.imglist.splice(index,1);
        },
        OpenDeskew(){ 
          if (this.rectifying == false) { 
              this.OpenCorrect("0");
          } else { 
              this.OpenCorrect("1");
          }
        }, 
        OpenAutoScan(){
          if (this.autocamera == false) { 
              this.AutoScan("0");
          } else { 
              this.AutoScan("1");
          }
        },
        AutoScan(){
            var url = window._CONFIG['WindowsGPYUrl']+"/video=movedetec"
            var data = {
                "movedetecflag": "1",           // 开启自动拍照
                "listpath": "D://httpcamera",   // 图片保存目录
                "filepath": "LT"                // 图片名称前缀
            }
            axios.post(url, JSON.stringify(data)).then((res)=>{
               
              if (res.code === "0") {
                    console.log("开启自动拍照成功")
                    console.log(res.data);
                    AutoScan();
                } else {
                  console.log("开启自动拍照失败");
                }
            })
          
        },
        set(){
          
          this.modelvisible = true;
        },
        ModelOk(){
          console.log(this.rectifying)
          console.log(this.autocamera)
          console.log(this.quality)
          console.log(this.ColorMode)
          this.ColorMode = 2;
          // this.modelvisible = false;
        },
        handleOk(){     
          if (this.imglist.length == 0){
            this.$message.error("请上传文件");
          } 
          this.iconLoading = true;
          this.hubmit = true;     
          this.close_view1();
          this.$emit('ok','carmera',this.imglist)
        },
        OpenCorrect(lx){
          var data = {
              "camidx": "0",  // 摄像头索引，0：主头；1：副头
              "open": lx     // 状态，0：关；1：开
          }  
          axios.post(window._CONFIG['WindowsGPYUrl']+"/dvideo=cameradeskew", JSON.stringify(data)).then((res)=>{
             
          })
        },
        showwindow(){
          this.visible = true;
        },
        // 打开主头视频
        OpenCamera(){
          this.openLoading = true;
          console.log("打开主头视频")
          var random = Math.random(); //创建随机数
          document.getElementById("view1").src = "";
          document.getElementById("view1").src = window._CONFIG['WindowsGPYUrl']+"/video=stream&camidx=0?" + random; 
          this.openLoading = false;
          
   
        },
        // 关闭主头视频
        close_view1(){ 
          this.closeLoading = true;
          let data = {"camidx": "0"}
          axios.post(window._CONFIG['WindowsGPYUrl']+"/video=close", JSON.stringify(data)).then(()=>{
            document.getElementById('view1').src = ''
            this.closeLoading = false;
          }) 
        },

        rotate(angle){
          let data = {"camidx": '0', "rotate": String(angle)}
          this.rotatv+=angle;
          console.log("角度",this.rotatv)
          if (this.rotatv % 180 == 0)
          {
            this.viewheight = 282;
            this.viewwidth = 400;
          }else {
            this.viewheight = 400;
            this.viewwidth = 282;
          }
          console.log(this.viewheight)
          axios.post(window._CONFIG['WindowsGPYUrl']+"/video=rotate", JSON.stringify(data)).then((res)=>{
           
          })
  
        },
        // 右转
        rotate270(){
          let  data = {
            "camidx": "0",
            "rotate": "270"
          }
          axios({url:"/gpy/video=rotate",  data:data,
            headers: {"Access-Control-Allow-Origin": "*"},method:'post'}
          ).then((res) =>
          { 
            // add_img(res.photoBase64);
          })
        },
        // 主头拍照并保存本地
        save_image_scan(){
          let data = {
            "filepath": "D:\\a.jpg",
            "rotate": "0",
            "cutpage": "0",
            "deskew": "1",
            "deskewval": "-20",
            "camidx": "0",
            "ClolorMode": "0",
            "quality": "0"
          }
          axios({url:"/gpy/video=grabimage",  data:data,
            headers: {"Access-Control-Allow-Origin": "*"},method:'post'}
          ).then((res) =>
          { 
            // add_img(res.photoBase64);
          }) 
        },
        // 用于输出日志信息
        my_log(msg){
          let element = document.getElementById('mylog')
          let old_val = element.innerHTML
          let date = new Date().toString().slice(16, 24)
          element.innerHTML = date + '&nbsp;&nbsp;' + msg + '<br>' + old_val;
        },
  
        add (obj) {
          this.modelDefault.pid=''
          this.edit(Object.assign(this.modelDefault , obj));
        },
        edit (record) {
          this.model = Object.assign({}, record);
          this.visible = true;
        },
        close () {
          this.$emit('close');
          this.visible = false;
          this.$refs.form.clearValidate()
        }, 
        handleCancel () {
          this.close()
        },
        submitSuccess(formData,flag){
          if(!formData.id){
            let treeData = this.$refs.treeSelect.getCurrTreeData()
            this.expandedRowKeys=[]
            this.getExpandKeysByPid(formData[this.pidField],treeData,treeData)
            this.$emit('ok',formData,this.expandedRowKeys.reverse());
          }else{
            this.$emit('ok',formData,flag);
          }
        },
        getExpandKeysByPid(pid,arr,all){
          if(pid && arr && arr.length>0){
            for(let i=0;i<arr.length;i++){
              if(arr[i].key==pid){
                this.expandedRowKeys.push(arr[i].key)
                this.getExpandKeysByPid(arr[i]['parentId'],all,all)
              }else{
                this.getExpandKeysByPid(pid,arr[i].children,all)
              }
            }
          }
        },
        getUrlBase64(url, ext, callback) {
            var canvas = document.createElement("canvas");   //创建canvas DOM元素
            var ctx = canvas.getContext("2d");
            var img = new Image;
            img.crossOrigin = 'Anonymous';
            img.src = "data:image/jpg;base64,"+url;
            img.onload = function () {
                canvas.height = img.height-100; //指定画板的高度,自定义
                canvas.width = img.width-100; //指定画板的宽度，自定义 
                ctx.drawImage(img, -40, -40, img.width-40, img.height-40); //参数可自定义
                var dataURL = canvas.toDataURL("image/" + ext);
                callback.call(this, dataURL); //回掉函数获取Base64编码
                canvas = null;
            };
        },
          // 拍照，本示例为拍照获取base64数据
        scan(view){  
          let data = {
            "filepath": "base64",
            "rotate": "0",
            "cutpage": "0",
            "camidx": "0",
            "ColorMode": "0",
            "quality": "3",
            "deskew":"1",
            "bAutoAdjust":"1"
          }
          axios.post(window._CONFIG['WindowsGPYUrl']+"/video=grabimage", JSON.stringify(data)).then((res)=>{
            // add_image(res.data.photoBase64) 
          })
        },
        GrabImage(){
          let jp =0;
          this.GrabLoading = true;
          let that  = this;
          if (this.rectifying==true){jp =1}

          var data = {
              "filepath": "",  //"D://test11.jpg"  指定路径  "base64" 不保存本地，返回base64  ""   保存默认路径下     
              "rotate": "0",      // 图像旋转角度，90的整数倍，默认："0"
              "deskew": jp,      // 纠偏（主头有效），参数：0:不纠偏；1:纠偏
              "deskewval": "0",       // 纠偏像素值：正常给0，正数时多裁，负数时少裁
              "camidx": 0,      // 摄像头索引，参数：0:主头；1:副头
              "quality": this.quality, //图片质量，图片保存本地调用。0:默认质量；1:高质量；2:较高质量；3:中质量；4:较低质量；5:低质量
              "ColorMode": this.ColorMode, // 色彩模式，图片保存本地时调用。0：彩色 1：灰色 2：黑白 3：白纸印章 4：去背景色(普通文件) 5:去背景色(身份证)
              "bIsPrint1to1": "0",   // 1:1打印有一点点偏差 是适用于身份证卡片之类  1:开启;  0 :关闭
          };
          var url = window._CONFIG['WindowsGPYUrl']+"/video=grabimage";
          axios.post(url, JSON.stringify(data)).then((res)=>{
            console.log("返回信息",res);
            // add_image(res.data.photoBase64) 
            // that.getUrlBase64(res.data.data.img, 'jpg', function (base64) {  
              this.GrabLoading = false;
              this.imglist.push(res.data.photoBase64)

              // 获取设置了滚动属性的div标签
              const div = document.getElementById('container');
              // 设置滚动的顶点坐标为滚动的总高度
              div.scrollTop = div.scrollHeight + 50;
              console.log(div.scrollTop) 
            // });
            
          })
           
          

        }
        
      }
    }
  
  
    // 传递图片base64，缩略图框生成图片用来显示,并添加到PDF队列
    function add_img(img_base64){
      let img = document.createElement('img');
      img.id = 'hu' + String(Math.random());
      img.src = "data:image/jpg;base64," + img_base64;
      img.oncontextmenu = showOperation;
      img.style.width = '80px';
      img.style.height = '80px';
      document.getElementById('my_thumbnail').appendChild(img)
    }
  </script>
  <style>
  /* 全局 */
  #app {
    font-family: Avenir, Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    color: #2c3e50;
    margin-top: 10px;
  }
  /* 视频预览 */
  #view1, #view2{
    width: 300px; 
    height: 212px; 
    border: 1px solid rgba(185, 181, 181, 0.404);
    margin-right: 5px;
  }
  /* 缩略图 */
  #suoluetu{
    width: 100%; 
    border: 1px solid rgba(185, 181, 181, 0.404);
  }
  #suoluetu img{
    margin-right: 10px;
  }
  /* 操作按钮 */
  #myactive{
    border: 1px solid yellowgreen;
    margin-top: 10px;
    padding: 10px 5px;
  }
  /* 操作日志 */
  #mylog{
    border: 1px solid black;
    padding: 10px;
    margin-top: 10px;
    overflow: auto;
  }
  .ant-spin-container{
    height: 100%;
  }
  .ant-form ant-form-horizontal{
    height: 100%;
  }
  .table-operator{
    margin-top: 20px;
    text-align: right; } 
  /* .hopic{
    .delete-img { 
    }
    &:hover {
      .delete-img {
        display: block;
        position: absolute;
        width: 105px;
        height: 85px;
        line-height: 85px;
        margin-top:-85px;
        background: rgba(59, 60, 61, 0.5);  
        cursor: pointer;
        text-align: center;
        i {
          
          display: block;
          font-size: 24px;
          color: white;
        }
      }
    }
  } */
  </style>